<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* RESOURCEEDIT class
*
* $Header: /cvsroot/wikindx/wikindx3/core/resource/RESOURCEEDIT.php,v 1.33 2007/04/28 09:25:28 sirfragalot Exp $
*****/
class RESOURCEEDIT
{
// Constructor
	function RESOURCEEDIT($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/HTML.php");
		include_once("core/html/FORM.php");
		$this->html = new HTML();
		include_once("core/resource/RESOURCEFORM.php");
		$this->form = new RESOURCEFORM($this->db, $this->vars);
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
	}
// edit a resource
	function resource($error = FALSE)
	{
		include_once("core/resource/VALIDATEINPUT.php");
		$this->validate = new VALIDATEINPUT($this->db, $this->vars, $this);
		$this->template->setVar('heading', $this->messages->text("heading", "editResource"));
		$this->template->setVar('formStart', FORM::formHeader("resourceEdit"));
		$conversion = FALSE;
		if($error)
			$pString = $error;
		else
			$pString = FALSE;
// Required in RESOURCE::gatekeep() if $WIKINDX_ORIGINATOR_EDITONLY == TRUE
		if(array_key_exists('id', $this->vars))
			$pString .= FORM::hidden('id', $this->vars['id']);
// Some resource types have no creators so need to skip to stage3
		if(isset($this->vars['method']) && ($this->vars['method'] == 'stage2') 
			&& (($this->vars['resource_type'] == 'bill') || ($this->vars['resource_type'] == 'hearing') ||
			($this->vars['resource_type'] == 'statute')))
			$this->vars['method'] = 'stage3';
		if(!isset($this->vars['method']))
		{
			$this->session->clearArray('resource');
// write to the session from the database
			$this->loadSession();
			$pString .= $this->form->stage1(FALSE);
			$this->template->setVar('body', $pString);
			$this->template->setVar('formEnd', FORM::formEnd());
			return $this->template->process();
		}
		if(array_key_exists('resource_changeCollection', $this->vars)) // overrides change of resource type
		{
			$sessionVars = $this->validate->stage1(TRUE);
			$type = $this->vars['resource_type'];
			include_once("core/collection/COLLECTION.php");
			$collection = new COLLECTION($this->db);
			include_once("core/collection/COLLECTIONMAP.php");
			$map = new COLLECTIONMAP();
			if(array_key_exists($type, $map->collectionTypes))
			{
				$collections = $collection->grabAll($map->collectionTypes[$type]);
				if($collections) // collections exist for this resource type/  Print the form here
				{
					$pString .= $this->form->stage1a($collections, $sessionVars, TRUE, $this->session->getVar("resource_collectionId"));
					$this->template->setVar('body', $pString);
					$this->template->setVar('formEnd', FORM::formEnd());
					return $this->template->process();
				}
				else
					$this->vars['method'] = 'stage3';
			}
			else
				$this->vars['method'] = 'stage3';
			if(!array_key_exists('resource_editError', $this->vars))
				$this->triageSession();
		}
// If we're converting resource type, skip to stage3
		else if(array_key_exists('resource_typeConvert', $this->vars) && 
			($this->vars['resource_type'] != $this->vars['resource_typeConvert']))
		{
			$this->template->setVar('heading', $this->messages->text("heading", "convertResourceType"));
			if(array_key_exists('resource_collectionId', $this->vars))
				$this->vars['method'] = 'stage3';
			else
			{
				$sessionVars = $this->validate->stage1();
				$type = $this->vars['resource_typeConvert'];
				include_once("core/collection/COLLECTION.php");
				$collection = new COLLECTION($this->db);
				include_once("core/collection/COLLECTIONMAP.php");
				$map = new COLLECTIONMAP();
				if($type && array_key_exists($type, $map->collectionTypes))
				{
					$collections = $collection->grabAll($map->collectionTypes[$type]);
					if($collections) // collections exist for this resource type/  Print the form here
					{
						$pString .= $this->form->stage1a($collections, $sessionVars, TRUE);
						$this->template->setVar('body', $pString);
						$this->template->setVar('formEnd', FORM::formEnd());
						return $this->template->process();
					}
					else
						$this->vars['method'] = 'stage3';
				}
				else
					$this->vars['method'] = 'stage3';
			}
			$this->session->setVar("resource_typeConvert", $this->vars['resource_typeConvert']);
			if(!array_key_exists('resource_editError', $this->vars))
				$this->triageSession();
			$conversion = TRUE;
//			$this->session->setVar("resource_type", $this->vars['resource_typeConvert']);
		}
		else
		{
			$this->session->delVar("resource_typeConvert");
			$conversion = FALSE;
		}
		if(!isset($this->vars['method']))
		{
			$this->session->clearArray('resource');
// write to the session from the database
			$this->loadSession();
			$pString .= $this->form->stage1(FALSE);
		}
		else if($this->vars['method'] == 'stage1a')
		{
			$sessionVars = $this->validate->stage1a(TRUE);
			$pString .= $this->form->stage2($sessionVars, FALSE);
		}
		else if($this->vars['method'] == 'stage2')
		{
			$sessionVars = $this->validate->stage1(TRUE);
			$pString .= $this->form->stage2($sessionVars, FALSE);
		}
		else if($this->vars['method'] == 'stage3')
		{
			if(!$conversion)
				unset($this->validate->vars['resource_typeConvert']);
			$sessionVars = $this->validate->stage2(TRUE);
// No contributors, skip to stage3
			if(!$pString .= $this->form->stage3($sessionVars, FALSE))
				$pString .= $this->form->stage4($sessionVars, FALSE);
			$this->template->setVar('formStart', FORM::formHeader("resourceWrite"));
		}
		$this->template->setVar('body', $pString);
		$this->template->setVar('formEnd', FORM::formEnd());
		return $this->template->process();
	}
/*
* Write 'resource_' values to the session from the database
*
* @author Mark Grimshaw
* @version 1
*/
	function loadSession()
	{
// missing resource id
		if(!isset($this->vars['id']) || !$this->vars['id'])
			$this->badInputBomb($this->errors->text("inputError", "missing", " (" . 
			$this->messages->text("resources", "id") . ")"));
		include_once("core/resource/RESOURCEMAP.php");
		$map = new RESOURCEMAP();
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($this->db);
// fields from WKX_resource_note, WKX_resource_category, WKX_resource_abstract and WKX_resource_keyword:
		$array = array("text", "categories", "keywords", "abstract");
		$sql = $this->db->selectNoExecute(array("WKX_resource"), array_merge($stmt->listFields(), $array), 
			$stmt->selectJoin());
		$sql .= " WHERE WKX_resource.id=" . $this->db->tidyInput($this->vars['id']);
		$row = $this->db->fetchRow($this->db->query($sql));
// Serialize and write row to session -- stores publisher/collection IDs in case we need to remove in RESOURCEWRITE 
// and stores creator information so that we can write creator details to session in RESOURCENEW stage2() (necessary 
// in case user hits back button when editing a resource.
		$this->session->setVar("resourceEditRow", serialize($row));
// categories becomes group_ids etc.
		$temp['group_ids'] = $row['categories'];
		if($row['keywords'])
			$temp['keyword_ids'] = $row['keywords'];
// text from WKX_resource_note becomes note
		if($row['text'])
			$temp['note'] = $row['text'];
// Add other fields from the database
		$fieldArray = array('resourceId', 'type', 'noSort', 'title', 'subtitle', "shortTitle", 
			 'transNoSort', 'transTitle', 'transSubtitle');
		foreach($fieldArray as $field)
		{
			if($row[$field])
				$temp[$field] = $row[$field];
		}
// Keep record of full title in case title is being edited to remove the noSort value
		if(array_key_exists('noSort', $temp))
			$temp['fullTitle'] = $temp['noSort'] . ' ' . $temp['title'];
		else if(array_key_exists('title', $temp))
			$temp['fullTitle'] = $temp['title'];
		else
			$temp['fullTitle'] = $temp['title'] = "(no title)";
		if(array_key_exists('transNoSort', $temp))
			$temp['fullTransTitle'] = $temp['transNoSort'] . ' ' . $temp['transTitle'];
		else if(array_key_exists('transTitle', $temp))
			$temp['fullTransTitle'] = $temp['transTitle'];
		else
			$temp['fullTransTitle'] = $temp['transTitle'] = "(no title)";
		$type = $row['type'];
		foreach($row as $key => $value)
		{
			if(array_search($key, $map->{$type}['possible']) !== FALSE)
				$temp[$key] = $value;
		}
// Special cases...
// put $row['collectionTitle'] into $temp['collection']
		if($row['collectionTitle'])
		{
			$temp['collection'] = $row['collectionTitle'];
			$this->session->setVar("resource_collectionId", $row['collection']);
		}
		else
			$this->session->delVar("resource_collection");
		if($row['collectionTitleShort'])
			$temp['collectionShort'] = $row['collectionTitleShort'];
		if(($type == 'proceedings_article') || ($type == 'proceedings'))
		{
			$recordSet = $this->db->select(array('WKX_publisher'), array('publisherName', 'publisherLocation'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['miscField1']));
			$confPublisherRow = $this->db->fetchRow($recordSet);
			$temp['confPublisherName'] = $confPublisherRow['publisherName'];
			$temp['confPublisherLocation'] = $confPublisherRow['publisherLocation'];
		}
		if(($type == 'book') || ($type == 'book_article') || ($type == 'book_chapter'))
		{
			$recordSet = $this->db->select(array('WKX_publisher'), array('publisherName', 'publisherLocation'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['miscField1']));
			$transPublisherRow = $this->db->fetchRow($recordSet);
			if(!empty($transPublisherRow))
			{
				$temp['transPublisherName'] = $transPublisherRow['publisherName'];
				$temp['transPublisherLocation'] = $transPublisherRow['publisherLocation'];
			}
		}
		if(!$this->session->writeArray($temp, "resource"))
			$this->badInputBomb($this->errors->text("sessionError", "write"));
	}
// set numcreators, names etc.  Need to manipulate $temp directly
	function addNames($row, &$temp)
	{
		$creatorTypes = array("creator1", "creator2", "creator3", "creator4", "creator5");
		$names = array("surname", "firstname", "initials", "prefix");
		foreach($creatorTypes as $creatorType)
		{
			if($row[$creatorType])
				$temp['num_' . $creatorType] = sizeof(explode(',', $row[$creatorType]));
		}
		$sqlArray = $names;
		$sqlArray[] = 'id';
		foreach($creatorTypes as $creatorType)
		{
			if($row[$creatorType])
			{
				$condition = array();
				$ids = explode(',', $row[$creatorType]);
				foreach($ids as $id)
					$condition[] = $this->db->formatField('id') . "=" . 
					$this->db->tidyInput($id);
				$recordset = $this->db->select(array('WKX_creator'), $sqlArray, 
					" WHERE " . implode(" OR ", $condition));
				while($line = $this->db->loopRecordSet($recordset))
				{
					foreach($names as $name)
					{
						if($name == 'initials')
							$line[$name] = str_replace(" ", ".", $line[$name]) . ".";
						$collectNames[$line['id']][$name] = $line[$name];
					}
				}
				$index = 1;
				foreach($ids as $id)
				{
					foreach($names as $name)
					{
						if(!$collectNames[$id][$name])
							continue;
						$temp[$creatorType . "_" . $index . "_" . $name] =
							$collectNames[$id][$name];
					}
					$index ++;
				}
			}
		}
		return $temp;
	}
// When converting a resource type, remove session variables that don't match
	function triageSession()
	{
		include_once("core/resource/RESOURCEMAP.php");
		$map = new RESOURCEMAP();
		$oldType = $this->vars['resource_type'];
		$this->session->setVar("resource_oldType", $oldType);
		$newType = $this->vars['resource_typeConvert'];
		foreach($map->{$oldType}['resource'] as $key => $value)
		{
			if(array_search($value, $map->{$newType}['resource']) === FALSE)
				$this->session->delVar("resource_$key");
		}
		foreach($map->{$oldType}['resource_misc'] as $key => $value)
		{
			if(array_search($value, $map->{$newType}['resource_misc']) === FALSE)
				$this->session->delVar("resource_$key");
		}
		foreach($map->{$oldType}['resource_year'] as $key => $value)
		{
			if(array_search($value, $map->{$newType}['resource_year']) === FALSE)
				$this->session->delVar("resource_$key");
		}
		foreach($map->{$oldType}['resource_creator'] as $key => $value)
		{
			if(!array_key_exists($key, $map->{$newType}['resource_creator']))
				$this->session->delVar("resource_$key");
		}
		if((array_search('pageStart', $map->{$oldType}['possible']) !== FALSE) &&
			(array_search('pageStart', $map->{$newType}['possible']) === FALSE))
				$this->session->delVar("resource_pageStart");
		if((array_search('pageEnd', $map->{$oldType}['possible']) !== FALSE) &&
			(array_search('pageEnd', $map->{$newType}['possible']) === FALSE))
				$this->session->delVar("resource_pageEnd");
		if((array_search('publisherName', $map->{$oldType}['possible']) !== FALSE) &&
			(array_search('publisherName', $map->{$newType}['possible']) === FALSE))
		{
			$this->session->delVar("resource_publisherName");
			$this->session->delVar("resource_publisherLocation");
		}
		if((array_search('collection', $map->{$oldType}['possible']) !== FALSE) &&
			(array_search('collection', $map->{$newType}['possible']) === FALSE))
				$this->session->delVar("resource_collection");
	}
// Error handling.  Everything sent back to function editResource which prints error message.
// Reset $this->vars['method'] for editResource to parse function correctly.
	function badInput($error, $method = FALSE)
	{
		include_once("core/html/CLOSE.php");
		if($method)
			$this->vars['method'] = $method;
		else if(array_key_exists('method', $this->vars))
			unset($this->vars['method']);
		new CLOSE($this->db, $this->resource($error));
	}
// Error handling.  Bomb out.
	function badInputBomb($error)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $error);
	}
}
?>
